package cc.fs.zhihu.ui

import android.animation.ObjectAnimator
import android.animation.ValueAnimator
import android.content.Context
import android.content.Intent
import android.content.pm.ActivityInfo
import android.os.Bundle
import android.support.v7.widget.Toolbar
import android.util.Log
import android.view.SurfaceHolder
import android.view.SurfaceView
import android.view.View
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.SeekBar
import android.widget.TextView
import cc.fs.zhihu.R
import cc.fs.zhihu.beans.VideoBean1
import cc.fs.zhihuapp.utils.bindView
import tv.danmaku.ijk.media.player.IjkMediaPlayer
import java.math.BigInteger
import java.text.SimpleDateFormat
import java.util.*


class VideoActivity : BaseActivity(), SurfaceHolder.Callback {

    companion object {
        fun start(context: Context, video: VideoBean1) {
            val intent = Intent(context, VideoActivity::class.java)
            intent.putExtra("video", video)
            context.startActivity(intent)
        }
    }

    val toolbar: Toolbar by bindView(R.id.toolbar)
    val time: TextView by bindView(R.id.time)
    val bottomLayout: RelativeLayout by bindView(R.id.bottomLayout)
    val surfaceView: SurfaceView by bindView(R.id.videoView)
    val backBtn: ImageView by bindView(R.id.backBtn)
    val playBtn: ImageView by bindView(R.id.playBtn)
    val forwardBtn: ImageView by bindView(R.id.forwardBtn)
    val progressbar: SeekBar by bindView(R.id.progressbar)
    val timer = Timer()
    var video : VideoBean1 ?= null

    val timeTask: MyTimeTask = MyTimeTask()

    val outBottomAnimation: Animation by lazy {
        AnimationUtils.loadAnimation(this, R.anim.bottom_play_out)
    }

    val inBottomAnimation: Animation by lazy {
        AnimationUtils.loadAnimation(this, R.anim.bottom_play_in)
    }

    val outTopAnimation: Animation by lazy {
        AnimationUtils.loadAnimation(this, R.anim.top_play_out)
    }

    val inTopAnimation: Animation by lazy {
        AnimationUtils.loadAnimation(this, R.anim.top_play_in)
    }

    fun formatVideoTime(t: Int): String {
        val timeBuilder = StringBuilder()
        var time: Int = t / 1000;//获得秒
        var hour: Int = 0
        var minute: Int = 0
        var second: Int = 0
        hour = time / 3600
        if (hour > 0) {
            timeBuilder.append("" + hour + ":")
            time = time.minus(3600 * hour)
        }

        minute = time / 60
        if (minute > 0) {
            if (minute > 9) {
                timeBuilder.append("" + minute + ":")
            } else {
                timeBuilder.append("0" + minute + ":")
            }
            time = time.minus(60 * minute)
        } else {
            timeBuilder.append("00:")
        }

        second = time
        if (second > 9) {
            timeBuilder.append("" + second + "")
        } else {
            timeBuilder.append("0" + second)
        }

        return timeBuilder.toString()
    }

    fun getOffsetTime(clickTime: Int, nowTime: Int): Int {
        val cTime: Int = clickTime
        val nTime: Int = nowTime
        return cTime.minus(nTime)
    }

    fun getTime(l: Long): String {
        val time = l and 0xffffffff

        val date = Date(time)
        val builder = StringBuilder()
        if (date.hours != null) {
            builder.append("" + date.hours + ":")
        }

        if (date.minutes != null) {
            if (date.minutes > 9) {
                builder.append("" + date.minutes + ":")
            } else {
                builder.append("0" + date.minutes + ":")
            }
        } else {
            builder.append("00:")
        }

        if (date.seconds != null) {
            if (date.seconds > 9) {
                builder.append("" + date.seconds + "")
            } else {
                builder.append("0" + date.seconds + "")
            }
        } else {
            builder.append("00")
        }

        return builder.toString()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_video)

        video =  intent.getParcelableExtra("video")
        toolbar.setNavigationIcon(R.drawable.ic_back)
        toolbar.title = video?.title
        setSupportActionBar(toolbar)

        setUpVideoView()
    }

    var surfaceHolder: SurfaceHolder ? = null
    var ijkplayer: IjkMediaPlayer ? = null
    fun setUpVideoView() {
        requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
        surfaceHolder = surfaceView.holder
        surfaceHolder?.addCallback(this)
        surfaceHolder?.setFixedSize(320, 220)
        surfaceHolder?.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS)

        backBtn.setOnClickListener {
            val position: Long = (ijkplayer?.currentPosition ?: 0) - 20000
            ijkplayer?.seekTo(position)
        }
        playBtn.setOnClickListener {
            if (ijkplayer!!.isPlaying) {
                ijkplayer?.pause()
                playBtn.setImageResource(R.drawable.icon_play)
            } else {
                ijkplayer?.start()
                playBtn.setImageResource(R.drawable.icon_pause)
            }
        }
        forwardBtn.setOnClickListener {
            val position: Long = (ijkplayer?.currentPosition ?: 0 ) + 20000
            ijkplayer?.seekTo(position)
        }

        inBottomAnimation.setAnimationListener(object : Animation.AnimationListener {
            override fun onAnimationRepeat(p0: Animation?) {
            }

            override fun onAnimationEnd(p0: Animation?) {
                bottomLayout.visibility = View.VISIBLE
            }

            override fun onAnimationStart(p0: Animation?) {
            }

        })

        outBottomAnimation.setAnimationListener(object : Animation.AnimationListener {
            override fun onAnimationRepeat(p0: Animation?) {
            }

            override fun onAnimationEnd(p0: Animation?) {
                bottomLayout.visibility = View.GONE
            }

            override fun onAnimationStart(p0: Animation?) {
            }

        })

        outTopAnimation.setAnimationListener(object : Animation.AnimationListener {
            override fun onAnimationRepeat(p0: Animation?) {
            }

            override fun onAnimationStart(p0: Animation?) {
            }

            override fun onAnimationEnd(p0: Animation?) {
                toolbar.visibility = View.GONE
            }
        })

        inTopAnimation.setAnimationListener(object : Animation.AnimationListener {
            override fun onAnimationRepeat(p0: Animation?) {
            }

            override fun onAnimationEnd(p0: Animation?) {
                toolbar.visibility = View.VISIBLE
            }

            override fun onAnimationStart(p0: Animation?) {
            }

        })

        surfaceView.setOnClickListener {
            if (bottomLayout.visibility == View.VISIBLE) {
                bottomLayout.startAnimation(outBottomAnimation)
            } else {
                bottomLayout.startAnimation(inBottomAnimation)
            }

            if (toolbar.visibility == View.VISIBLE) {
                toolbar.startAnimation(outTopAnimation)
            } else {
                toolbar.startAnimation(inTopAnimation)
            }

        }

        progressbar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(p0: SeekBar?, p1: Int, p2: Boolean) {
            }

            override fun onStartTrackingTouch(p0: SeekBar?) {
                if (ijkplayer?.isPlaying ?: false) {
                    timeTask.isUpdate = false
                    runDelay({
                        val offsetTime = ijkplayer!!.currentPosition + getOffsetTime(progressbar!!.progress, ijkplayer!!.currentPosition.toInt())
                        ijkplayer?.seekTo(offsetTime)
                        timeTask.isUpdate = true
                    }, 50)
                }
            }

            override fun onStopTrackingTouch(p0: SeekBar?) {
            }

        })

    }

    override fun surfaceChanged(p0: SurfaceHolder?, p1: Int, p2: Int, p3: Int) {
    }

    override fun surfaceDestroyed(p0: SurfaceHolder?) {
    }

    override fun surfaceCreated(p0: SurfaceHolder?) {
        ijkplayer = IjkMediaPlayer()
        ijkplayer?.setDisplay(surfaceHolder)
        ijkplayer?.dataSource = video?.path
        ijkplayer?.prepareAsync()
        ijkplayer?.start()
        ijkplayer?.setOnCompletionListener {
            finish()
        }

        timer.schedule(timeTask, 0, 1000)
        playBtn.setImageResource(R.drawable.icon_pause)
    }

    override fun onPause() {
        if (ijkplayer!!.isPlaying) {
            ijkplayer?.stop()
            playBtn.setImageResource(R.drawable.icon_pause)
            timeTask.cancel()
        }
        super.onPause()
    }

    override fun onDestroy() {
        timeTask.cancel()
        ijkplayer?.stop()
        ijkplayer?.release()
        super.onDestroy()
    }

    inner class MyTimeTask : TimerTask() {
        var isUpdate: Boolean = true
        override fun run() {
            if (isUpdate && ijkplayer?.isPlaying ?: false) {
                runOnUiThread {
                    progressbar.max = ijkplayer!!.duration.toInt()
                    progressbar.progress = ijkplayer!!.currentPosition.toInt()
                    time.text = formatVideoTime(progressbar.progress) + "/" + formatVideoTime(progressbar.max)
                }
            }
        }
    }
}
